package com.naiterui.ehp.bs.ds.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.naiterui.ehp.bs.ds.common.constants.CacheConstants;
import com.naiterui.ehp.bs.ds.modules.sys.entity.UserRole;
import com.naiterui.ehp.bs.ds.modules.sys.mapper.UserRoleMapper;
import com.naiterui.ehp.bs.ds.modules.sys.service.IUserRoleService;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户与角色对应关系
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = {CacheConstants.USER_MENU_LIST, CacheConstants.PERMISSION_CACHE_PREFIX}, key = "#userId", allEntries = true)
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {
        // 先删除用户与角色关系
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        super.remove(new QueryWrapper<>(userRole));
        if (roleIdList.isEmpty()) {
            return;
        }
        // 保存用户与角色关系
        super.saveBatch(roleIdList.stream().map(roleId -> new UserRole(userId, roleId)).collect(Collectors.toList()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] roleIds) {
        this.baseMapper.deleteBatch(roleIds);
    }

    @Override
    public List<Long> queryRoleIdList(Long id) {
        return this.baseMapper.queryRoleIdList(id);
    }
}
